package com.zrl.project.controller;

import com.zrl.project.common.*;
import com.zrl.project.exception.BusinessException;
import com.zrl.project.model.VO.userVO.ModifyUserPasswordVO;
import com.zrl.project.model.entity.User;
import com.zrl.project.model.request.UserAddRequest;
import com.zrl.project.model.request.UserLoginRequest;
import com.zrl.project.model.request.UserRegisterRequest;
import com.zrl.project.model.request.UserSearchRequest;
import com.zrl.project.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

import static com.zrl.project.common.Admin.isAdmin;
import static com.zrl.project.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author: zrl
 * @date: 2023/2/24 16:33
 * @description:
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Value("${image.url}")
    public  String URL;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(id);
    }


    @PostMapping("/login")
    public BaseResponse<String> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if (userLoginRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String token = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(token);
    }


    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(){
        User safetyUser = UserHolder.getUser();
        return ResultUtils.success(safetyUser);
    }

    @PostMapping("/search")
    public BaseResponse<List<User>> searchUser(
            @RequestBody(required = false) UserSearchRequest userSearchRequest
            ){
        //仅管理员可查询
        if (!isAdmin()){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        List<User> result = null;
        if (userSearchRequest != null){
            String userName = userSearchRequest.getUserName();
            String userAccount = userSearchRequest.getUserAccount();
            Integer gender = userSearchRequest.getGender();
            Integer role = userSearchRequest.getRole();
            Integer userStatus = userSearchRequest.getUserStatus();

            result = userService.searchUsers(userName,userAccount,gender,role,userStatus);
        }else {
            result = userService.list();
        }

        return ResultUtils.success(result);
    }

    @PostMapping("/addUser")
    public BaseResponse<Long> deleteUser(@RequestBody UserAddRequest adduser, HttpServletRequest request){

        if (adduser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = adduser.getUserAccount();
        String userPassword = adduser.getUserPassword();

        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(adduser,user);
        Long id = userService.addUser(user);
        return ResultUtils.success(id);
    }


    @DeleteMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteUser(@PathVariable("id") Long id, HttpServletRequest request){

        //仅管理员可删除
        if (!isAdmin()){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    @PutMapping("/updateUser")
    public BaseResponse<Boolean> searchUser(
            @RequestBody User newUser,HttpServletRequest request){
        boolean result = userService.updateUserById(newUser,request);
        return ResultUtils.success(result);
    }

    @PostMapping("/modifyUserPassword")
    public BaseResponse<Boolean> modifyUserPassword(
            @RequestBody ModifyUserPasswordVO user){

        boolean result = userService.modifyUserPassword(user);
        return ResultUtils.success(result);
    }

    @PostMapping("/upload")
    public BaseResponse<String> upload(
            @RequestParam(value = "file")MultipartFile file){
        try {
            String fileName = "OPLP"+String.valueOf(System.currentTimeMillis()) + "image";
            QiniuUtils.upload2Qiniu(file.getBytes(), fileName);
            String finalUrl = URL + fileName;
            return ResultUtils.success(finalUrl);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"上传失败");
        }
    }



    @GetMapping("/getUserById/{userId}")
    public BaseResponse<User> getUserById(@PathVariable("userId") Long userId){
        User user = userService.getById(userId);
        return ResultUtils.success(user);
    }

    @PutMapping("/concernUser/{userId}")
    public BaseResponse<Boolean> concernUser(@PathVariable("userId") Long userId){
        Boolean res = userService.concernUser(userId);
        return ResultUtils.success(res);
    }

    @PutMapping("/noConcernUser/{userId}")
    public BaseResponse<Boolean> noConcernUser(@PathVariable("userId") Long userId){
        Boolean res = userService.noConcernUser(userId);
        return ResultUtils.success(res);
    }


    @GetMapping("/followedUser/{userId}")
    public BaseResponse<Boolean> followedUser(@PathVariable("userId") Long userId){
        Boolean res = userService.followedUser(userId);
        return ResultUtils.success(res);
    }

    @GetMapping("/getMyFans")
    public BaseResponse<List<User>> getMyFans(){
        List<User> res = userService.getMyFans();
        return ResultUtils.success(res);
    }

    @GetMapping("/getMyFollows")
    public BaseResponse<List<User>> getMyFollows(){
        List<User> res = userService.getMyFollows();
        return ResultUtils.success(res);
    }

    @DeleteMapping("/removeFan/{userId}")
    public BaseResponse<Boolean> removeFan(@PathVariable("userId") Long userId){
        Boolean res = userService.removeFan(userId);
        return ResultUtils.success(res);
    }
}